package cn.vihub.service.impl;

import cn.vihub.handler.MyRuntimeException;
import cn.vihub.param.ShopUserParam;
import cn.vihub.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.vihub.mapper.ShopUserToRoleMapper;
import cn.vihub.pojo.ShopUserToRole;
import cn.vihub.service.ShopUserToRoleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: 秋晚
 * @Date:  2025/7/18 16:14
 * @Description: 
 **/

@Service
@Transactional(rollbackFor = Exception.class)
public class ShopUserToRoleServiceImpl extends ServiceImpl<ShopUserToRoleMapper, ShopUserToRole> implements ShopUserToRoleService{

    @Override
    public Boolean binRole(ShopUserParam shopUserParam) {


        //先删除该用户id下的绑定角色
        remove(new LambdaQueryWrapper<ShopUserToRole>().eq(ShopUserToRole::getUserId,shopUserParam.getId()));

        //遍历传递的角色id集合   创建一个list集合用于存放封装遍历数据
        ArrayList<ShopUserToRole> list = new ArrayList<>();
        for (Integer roleId : shopUserParam.getRoleIds()) {
            ShopUserToRole shopUserToRole = new ShopUserToRole(null, shopUserParam.getId(), roleId);
            list.add(shopUserToRole);
        }
        return saveBatch(list);
    }

    @Override
    public List<ShopUserToRole> getRoleByUserId(Integer userId) {
        return list(new LambdaQueryWrapper<ShopUserToRole>().eq(ShopUserToRole::getUserId,userId));
    }

    @Override
    public void isUserByRoleId(Integer id) {
        //查询数量
        int count = count(new LambdaQueryWrapper<ShopUserToRole>().eq(ShopUserToRole::getRoleId, id));
        if(count>0){
            //存在抛出自定义异常  禁止删除
            throw new MyRuntimeException("角色下有关联用户禁止删除");
        }
    }
}
